<script setup>
// popup.js
document.addEventListener('DOMContentLoaded', async () => {
  // 初始化复选框状态
  chrome.storage.sync.get(['lgbtMark', 'queryMark', 'noteAudit'], result => {
    document.getElementById('lgbtMark').checked = result.lgbtMark !== false;
    document.getElementById('queryMark').checked = !!result.queryMark;
    document.getElementById('noteAudit').checked = result.noteAudit !== false;
    //document.getElementById('toggleSwitch').checked = result.toggleSwitch !== false;
  });

  // 添加事件监听
  document.getElementById("lgbtMark").addEventListener("change", (e) => {
    chrome.storage.sync.set({ lgbtMark: e.target.checked });
  });

  document.getElementById("queryMark").addEventListener("change", (e) => {
    chrome.storage.sync.set({ queryMark: e.target.checked });
  });

  document.getElementById("noteAudit").addEventListener("change", (e) => {
    chrome.storage.sync.set({ noteAudit: e.target.checked });
  });

  //document.getElementById("toggleSwitch").addEventListener("change", (e) => {
  //chrome.storage.sync.set({ toggleSwitch: e.target.checked });
  //});


  // 页面加载时检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  const savedUsername = localStorage.getItem('username');

  if (isLoggedIn && savedUsername) {
    document.getElementById('loginForm').style.display = 'none';
    showFeatureArea(savedUsername);
  } else {
    document.getElementById('loginForm').style.display = 'flex';
  }
  // 设置用户名的第一个字母为头像
  if (savedUsername) {
    document.getElementById('userAvatar').textContent = savedUsername.charAt(0).toUpperCase();
  }

  // 登录表单提交处理
  document.getElementById('loginForm').addEventListener('submit', async function (e) {
    e.preventDefault();

    const validPassword = 'd79f264fd6341a682f7f9ba0d00ca053f0fb2a9dd57d89d38d3f1a88232e7d7c'; // SHA-256 hash

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const rememberMe = true || document.getElementById('rememberMe').checked;// 暂时不设置记住我这个功能

    // 显示加载状态
    document.getElementById('loader').style.display = 'block';
    document.getElementById('loginError').style.display = 'none';

    try {
      // 1. 确保输入不为空
      if (!username || !password) {
        throw new Error('用户名和密码不能为空');
      }

      // 2. 直接使用PBKDF2加密（与validPassword匹配）
      const hash = await encryptPassword(password, 'pbkdf2', 'ps', 1);

      // 3. 打印调试信息（这里会打印）
      // console.log('加密结果:', hash);
      // console.log('正确密码:', validPassword);

      // 4. 比较哈希值
      if (hash === validPassword) {
        // 登录成功
        if (rememberMe) {
          localStorage.setItem('username', username);
          localStorage.setItem('isLoggedIn', 'true');
        }

        // 显示成功消息
        document.getElementById('loader').style.display = 'none';
        document.getElementById('successMessage').style.display = 'block';

        setTimeout(() => {
          showFeatureArea(username);
        }, 500);
      } else {
        throw new Error('用户名或密码错误');
      }
    } catch (error) {
      // 错误处理
      document.getElementById('loader').style.display = 'none';
      document.getElementById('loginError').textContent = error.message;
      document.getElementById('loginError').style.display = 'block';
    }
  });

  // 显示功能区域
  function showFeatureArea(username) {
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('successMessage').style.display = 'none';
    document.getElementById('featureArea').style.display = 'block';

    document.getElementById('userName').textContent = username;
    document.getElementById('userAvatar').textContent = username.charAt(0).toUpperCase();
  }

  // 退出登录
  document.getElementById('logoutBtn').addEventListener('click', function () {
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('username');

    chrome.storage.sync.set({ lgbtMark: false });
    chrome.storage.sync.set({ queryMark: false });
    chrome.storage.sync.set({ noteAudit: false });
    //chrome.storage.sync.set({ toggleSwitch: false });
    chrome.runtime.sendMessage({ action: 'clearAllTabs' });

    document.getElementById('featureArea').style.display = 'none';
    document.getElementById('loginForm').style.display = 'flex';
    document.getElementById('username').value = '';
    document.getElementById('password').value = '';
  });

  // 忘记密码处理
  document.getElementById('forgotPassword').addEventListener('click', function () {
    alert('请联系管理员重置密码\n2209848178@qq.com\n每天大量重复工作？可定制插件提升工作效率');
  });



  // 密码加密函数
  async function encryptPassword(password, algorithm, salt, iterations) {
    const encoder = new TextEncoder();
    const passwordBuffer = encoder.encode(password);
    const saltBuffer = encoder.encode(salt);

    switch (algorithm) {
      case 'sha256':
        const sha256Buffer = await crypto.subtle.digest('SHA-256', passwordBuffer);
        return bufferToHex(sha256Buffer);

      case 'sha512':
        const sha512Buffer = await crypto.subtle.digest('SHA-512', passwordBuffer);
        return bufferToHex(sha512Buffer);

      case 'pbkdf2':
        const pbkdf2Key = await crypto.subtle.importKey(
            'raw',
            passwordBuffer,
            { name: 'PBKDF2' },
            false,
            ['deriveBits']
        );

        const pbkdf2Buffer = await crypto.subtle.deriveBits(
            {
              name: 'PBKDF2',
              salt: saltBuffer,
              iterations: iterations,
              hash: 'SHA-256'
            },
            pbkdf2Key,
            256
        );

        return bufferToHex(pbkdf2Buffer);

      case 'bcrypt':
        // 模拟BCrypt (实际BCrypt需要外部库)
        const bcryptLike = await crypto.subtle.digest('SHA-512', encoder.encode(password + salt));
        const bcryptLikeHex = bufferToHex(bcryptLike);
        return `$2a$10$${salt}$${bcryptLikeHex.substring(0, 53)}`;

      default:
        throw new Error('不支持的加密算法');
    }
  }

  // ArrayBuffer转十六进制字符串
  function bufferToHex(buffer) {
    return Array.from(new Uint8Array(buffer))
        .map(b => b.toString(16).padStart(2, '0'))
        .join('');
  }

  const toggle = document.getElementById('activityToggle');
  const tabsList = document.getElementById('activeTabsList');

  // 获取当前标签页
  const [currentTab] = await chrome.tabs.query({ active: true, currentWindow: true });

  // 检查当前标签页是否已激活
  chrome.runtime.sendMessage({ action: 'checkStatus', tabId: currentTab.id }, (response) => {
    toggle.checked = response?.isActive || false;
  });



  // 切换状态
  toggle.addEventListener('change', () => {
    chrome.runtime.sendMessage({
      action: 'toggleActivity',
      tabId: currentTab.id,
      enable: toggle.checked
    });
    updateActiveTabsList();
  });



  // 更新活跃标签页列表
  async function updateActiveTabsList() {
    const response = await chrome.runtime.sendMessage({ action: 'getActiveTabs' });
    tabsList.innerHTML = '';

    if (response?.length > 0) {
      const tabs = await chrome.tabs.query({});
      response.forEach(tabId => {
        const tab = tabs.find(t => t.id === tabId);
        if (tab) {
          const tabEl = document.createElement('div');
          tabEl.className = 'tab-item';
          tabEl.textContent = tab.title || `标签页 ${tabId}`;
          tabsList.appendChild(tabEl);
        }
      });
    } else {
      const tabEl = document.createElement('div');
      tabEl.className = 'empty-content';
      tabEl.textContent = '没有活跃页面';
      tabsList.appendChild(tabEl);
      //tabsList.innerHTML = '<p style="text-align: center;width: 100%;display: block;">没有活跃页面</p>';
    }
  }



  // 初始加载列表
  updateActiveTabsList();
});


</script>

<template>
  <div class="header"  style="display: none">
    <span class="header-icon">⚡</span>
    <span>快捷键控制中心</span>
  </div>

  <!-- 登录表单 -->
  <form id="loginForm">
    <div class="form-group">
      <label for="username">用户名</label>
      <input type="text" id="username" placeholder="请输入用户名" required>
    </div>

    <div class="form-group">
      <label for="password">密码</label>
      <input type="password" id="password" placeholder="请输入密码" required>
    </div>

    <button type="submit" class="login-btn">登录</button>

    <div class="error-message" id="loginError">用户名或密码错误，请重试</div>

    <div class="login-options">
      <div class="remember-me">
        <!-- <input type="checkbox" id="rememberMe">
        <label for="rememberMe">记住我</label> -->
      </div>
      <div class="forgot-password" id="forgotPassword">忘记密码?</div>
    </div>
  </form>

  <div class="loader" id="loader">
    <div class="spinner"></div>
    <div style="margin-top: 8px; font-size: 13px;">正在验证...</div>
  </div>

  <div class="success-message" id="successMessage">
    登录成功！正在加载功能...
  </div>

  <!-- 功能区域（登录后显示） -->
  <div id="featureArea">
    <div class="user-info">
      <div class="user-details">
        <div class="user-avatar" id="userAvatar">U</div>
        <div class="user-name" id="userName">用户</div>
      </div>
      <button class="logout-btn" id="logoutBtn">退出登录</button>
    </div>

    <div class="feature-item" style="display: none">
      <span class="feature-name">LGBT模型标注</span>
      <label class="switch">
        <input id="lgbtMark" type="checkbox">
        <span class="slider"></span>
      </label>
    </div>

    <div class="feature-item" style="display: none">
      <span class="feature-name">QUERY时效标注</span>
      <label class="switch">
        <input id="queryMark" type="checkbox">
        <span class="slider"></span>
      </label>
    </div>

    <div class="feature-item" style="display: none">
      <span class="feature-name">恶劣笔记审核</span>
      <label class="switch">
        <input id="noteAudit" type="checkbox">
        <span class="slider"></span>
      </label>
    </div>

    <div class="feature-item">
      <span class="feature-name">当前页面是否活跃</span>
      <label class="switch">
        <input id="activityToggle" type="checkbox">
        <span class="slider"></span>
      </label>
    </div>
    <div class="feature-item">
      <div class="empty">
        <h3>活跃页面</h3>
        <div class="active-tabs" id="activeTabsList"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  width: 340px;
  padding: 16px;
  font-family: 'Segoe UI', Roboto, sans-serif;
  color: #333;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  min-height: 300px;
}

.header {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #202124;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 12px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.header-icon {
  font-size: 22px;
  color: #1a73e8;
}

/* 登录表单样式 */
#loginForm {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 15px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  animation: fadeIn 0.5s ease-in-out;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #5f6368;
}

.form-group input {
  padding: 12px 14px;
  border: 1px solid #dadce0;
  border-radius: 8px;
  font-size: 14px;
  transition: border 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #1a73e8;
  box-shadow: 0 0 0 2px rgba(26,115,232,0.1);
}

.login-btn {
  background: #1a73e8;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s, transform 0.1s;
  margin-top: 8px;
}

.login-btn:hover {
  background: #1765cc;
}

.login-btn:active {
  transform: scale(0.98);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 13px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 6px;
}

.forgot-password {
  color: #1a73e8;
  text-decoration: none;
  cursor: pointer;
}

.forgot-password:hover {
  text-decoration: underline;
}

/* 功能区域样式 */
#featureArea {
  display: none; /* 默认隐藏功能区域 */
  margin-top: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin-bottom: 20px;
}

.user-details {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #1a73e8, #6c8ef5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.user-name {
  font-weight: 500;
  font-size: 15px;
}

.logout-btn {
  background: transparent;
  border: 1px solid #dadce0;
  color: #5f6368;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.2s;
}

.logout-btn:hover {
  background: #f8f9fa;
}

.feature-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  margin-bottom: 10px;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.04);
  transition: transform 0.2s, box-shadow 0.2s;
}

.feature-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.08);
}

.feature-name {
  font-size: 14px;
  flex-grow: 1;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #1a73e8;
}

input:checked + .slider:before {
  transform: translateX(20px);
}

/* 错误消息 */
.error-message {
  color: #d93025;
  font-size: 13px;
  margin-top: 4px;
  display: none;
  text-align: center;
}

/* 加载状态 */
.loader {
  display: none;
  text-align: center;
  margin-top: 15px;
}

.spinner {
  border: 3px solid rgba(26, 115, 232, 0.2);
  border-top: 3px solid #1a73e8;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 登录成功消息 */
.success-message {
  text-align: center;
  background: #e8f0fe;
  color: #1a73e8;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  margin-top: 15px;
  display: none;
}

.version-info {
  text-align: center;
  font-size: 12px;
  color: #70757a;
  margin-top: 20px;
}
.active-tabs {
  display: flex;
  flex-direction: row;  /* 水平排列 */
  justify-content: flex-start; /* 左对齐 */
  flex-wrap: wrap;
}

.tab-item {
  padding: 5px;
  margin: 3px 0;
  background: #f5f5f5;
  border-radius: 3px;
}
.tab-item:not(:first-child) {
  margin-left: 5px; /* 设置间距 */
}
.empty {
  text-align: center;
  width: 100%;
}
.empty-content {
  margin-top: 10px;
  width: 100%;
  color: #999999;
}
</style>
